﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.ApplicationPages;
using System.Web.UI.WebControls;
using Winwise.SPWebConfig.Core;
using System.Collections.Generic;
using Winwise.SPWebConfig.Core.CodeModification;

namespace Winwise.SPWebConfig.UI
{
    public partial class AddEditCodeWebconfigModification : WebConfigDialogAdminPageBase
    {

        public void ApplyWebConfigModif(object sender, EventArgs e)
        {
            ApplyWebConfigModif(this.Selector.CurrentItem);
        }


        public void OnContextChange(object sender, EventArgs e)
        {
            if (this.Selector.CurrentItem != null)
            {
                SPWebApplication currentItem = this.Selector.CurrentItem;
                LinkManage.HRef = GetManageLink(currentItem);
                OnContextChange(currentItem);
            }
        }

        public override void FillWebConfigModif(WebConfigModification modif)
        {
            CodeWebConfigModification modifCode = modif as CodeWebConfigModification;
            modifCode.DisplayName = TBDisplayName.Text;
            modifCode.AssemblyName = TBAssemblyName.Text;
            modifCode.TypeName = TBTypeName.Text;

            modifCode.Zones.Clear();
            foreach (ListItem checkbox in CheckBoxZones.Items)
            {
                if (checkbox.Selected)
                {
                    modifCode.Zones.Add((SPUrlZone)Enum.Parse(typeof(SPUrlZone), checkbox.Text));
                }
            }
        }

        public override void UpdateMessage(string message)
        {
            LblResults.Text = message;
        } 

        public void AddModif(object sender, EventArgs e)
        {
            AddEditModif<CodeWebConfigModification>(this.Selector.CurrentItem);
        }


        public override void DataBind(WebConfigModification modif)
        {
            CodeWebConfigModification modifCode = modif as CodeWebConfigModification;
            TBDisplayName.Text = modifCode.DisplayName;
            TBAssemblyName.Text = modifCode.AssemblyName;
            TBTypeName.Text = modifCode.TypeName;

            CheckBoxZones.ClearSelection();
            foreach (var zone in modifCode.Zones)
            {
                CheckBoxZones.Items.FindByText(zone.ToString()).Selected = true;
            }
        }

        public override void UpdateErrorMessage(string message)
        {
            LabelErrorMessage.Text = message;
        }
    }
}
